package com.lxw.station.other;

import org.springframework.core.io.InputStreamResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class ZipFileDownloader {

    public static void main(String[] args) {
        String url = "https://storage.googleapis.com/chrome-for-testing-public/115.0.5790.170/win64/chrome-win64.zip";
        String destFilePath = "C:\\Users\\Administrator\\Desktop\\tmp\\chrome-win64.zip";

        try {
            downloadZipFile(url, destFilePath);
            System.out.println("File downloaded successfully!");
        } catch (IOException e) {
            System.err.println("Failed to download file: " + e.getMessage());
        }
    }

    public static void downloadZipFile(String url, String destFilePath) throws IOException {
        RestTemplate restTemplate = new RestTemplate();

        // 发送 GET 请求获取文件
        ResponseEntity<Resource> response = restTemplate.exchange(
                url,
                HttpMethod.GET,
                null,
                Resource.class
        );

        // 获取输入流
        Resource resource = response.getBody();
        if (resource == null) {
            throw new IOException("Failed to retrieve resource");
        }

        try (InputStream inputStream = resource.getInputStream();
             OutputStream outputStream = new FileOutputStream(new File(destFilePath))) {
            byte[] buffer = new byte[4096];
            int bytesRead;
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }
        }
    }
}

